package com.example.ruiji.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ruiji.common.RedisUtil;
import com.example.ruiji.common.Result;
import com.example.ruiji.entity.User;
import com.example.ruiji.mapper.UserMapper;
import com.example.ruiji.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    HttpSession httpSession;

    @Autowired
    UserMapper userMapper;

    @Override
    public Result<String> sendMsg(User user) {
        String phone = user.getPhone();
        if (StrUtil.isNotEmpty(phone)) {
            int intCode = RandomUtil.randomInt(1000, 9999);
            String code = Integer.toString(intCode);
            log.info("验证码为:" + code);
            //将验证码存入redis
            RedisUtil.setObject(user.getPhone(), code, 59, TimeUnit.SECONDS);
            return Result.error("发送失败");
        }
        return Result.success("发送成功");
    }

    @Override
    public Result<User> login(Map<String, String> map) {
        String phone = map.get("phone");
        String code = map.get("code");
        //从redis中取出验证码
        String cashCode = RedisUtil.getObject(phone, String.class);
        if (StrUtil.isNotEmpty(cashCode) && code.equals(cashCode)) {
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userMapper.selectOne(lambdaQueryWrapper);
            if (Objects.isNull(user)) {
                User newUser = new User();
                newUser.setPhone(phone);
                userMapper.insert(newUser);
            }
            httpSession.setAttribute("userId", user.getId());
            //登陆成功后删除redis中的验证码
            RedisUtil.deleteObject(phone);
            return Result.success(user);
        }
        return Result.error("登陆失败");
    }
}
